package ygw.study.tool;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 个人身份证号码校验工具类
 * </p>
 * <p>
 * Copyright:.All rights reserved.
 * </p>
 * <p>
 * Company:Zsoft
 * </p>
 * <p>
 * CreateDate: 2022/10/11
 * </p>
 * 
 * @author YuGongWen
 * @history Mender: YuGongWen；Date: 2022/10/11；
 */
public class IDCardNoValidateUtils {

    private static Map<String, String> map = new HashMap<>();

    private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    private static Logger logger = LoggerFactory.getLogger(IDCardNoValidateUtils.class);

    public static void main(String[] args) {
        boolean flag = IDCardNoValidateUtils.IDCardValidate("362401197309014456");
        System.out.println(flag);
        flag = IDCardNoValidateUtils.IDCardValidate("44040220081020915X");
        System.out.println(flag);
        flag = IDCardNoValidateUtils.IDCardValidate("1234");
        System.out.println(flag);

        flag = IDCardNoValidateUtils.IDCardValidate("830000197809280016");
        System.out.println(flag);

        flag = IDCardNoValidateUtils.IDCardValidate("830000195107120019");
        System.out.println(flag);
        flag = IDCardNoValidateUtils.IDCardValidate("421181199409109172");
        System.out.println(flag);
    }

    /**
     * 
     * @param IDStr
     * @return
     */
    public static boolean IDCardValidate(String IDStr){

        if (StringUtils.isBlank(IDStr)) {
            return false;
        }
        if (IDStr.length() != 15 && IDStr.length() != 18) {
            return false;
        }

        String[] ValCodeArr = { "1", "0", "X", "9", "8", "7", "6", "5", "4",
                "3", "2" };
        String[] Wi = { "7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7",
                "9", "10", "5", "8", "4", "2" };
        String Ai = "";
        String message = "";

        // ================ 数字 除最后以为都为数字 ================
        if (IDStr.length() == 18) {
            Ai = IDStr.substring(0, 17);
        } else if (IDStr.length() == 15) {
            Ai = IDStr.substring(0, 6) + "19" + IDStr.substring(6, 15);
        }
        if (isNumeric(Ai) == false) {
            message = "身份证15位号码都应为数字 ; 18位号码除最后一位外，都应为数字。";
            logger.debug(message);
            return false;
        }
        // =======================(end)========================

        // ================ 出生年月是否有效 ================
        String strYear = Ai.substring(6, 10);// 年份
        String strMonth = Ai.substring(10, 12);// 月份
        String strDay = Ai.substring(12, 14);// 月份
        String timeFormate = strYear + "-" + strMonth + "-" + strDay;
        if (isDate(timeFormate) == false) {
            message = "身份证生日无效。";
            logger.debug(message);
            return false;
        }
        GregorianCalendar gc = new GregorianCalendar();
        try {
            if ((gc.get(Calendar.YEAR) - Integer.parseInt(strYear)) > 150
                    || (gc.getTime().getTime() - dateFormat.parse(timeFormate).getTime()) < 0) {
                message = "身份证生日不在有效范围。";
                logger.debug(message);
                return false;
            }
        } catch (ParseException e) {
            //e.printStackTrace();
            logger.error("身份证生日日期转换失败",e);
            return false;
        }
        if (Integer.parseInt(strMonth) > 12 || Integer.parseInt(strMonth) == 0) {
            message = "身份证月份无效";
            logger.debug(message);
            return false;
        }
        if (Integer.parseInt(strDay) > 31 || Integer.parseInt(strDay) == 0) {
            message = "身份证日期无效";
            logger.debug(message);
            return false;
        }
        // =====================(end)=====================

        // ================ 地区码时候有效 ================
        Map<String, String> h = GetAreaCode();
        if (h.get(Ai.substring(0, 2)) == null) {
            message = "身份证地区编码错误。";
            logger.debug(message);
            return false;
        }
        // ==============================================

        // ================ 判断最后一位的值 ================
        int TotalmulAiWi = 0;
        for (int i = 0; i < 17; i++) {
            TotalmulAiWi = TotalmulAiWi
                    + Integer.parseInt(String.valueOf(Ai.charAt(i)))
                    * Integer.parseInt(Wi[i]);
        }
        int modValue = TotalmulAiWi % 11;
        String strVerifyCode = ValCodeArr[modValue];
        Ai = Ai + strVerifyCode;

        if (IDStr.length() == 18) {
            if (Ai.equals(IDStr) == false) {
                message = "身份证无效，不是合法的身份证号码";
                logger.debug(message);
                return false;
            }
        } else {
            return true;
        }
        // =====================(end)=====================
        return true;
    }

    private static Map<String, String> GetAreaCode() {
        if (map.size() == 0) {
            map.put("11", "北京");
            map.put("12", "天津");
            map.put("13", "河北");
            map.put("14", "山西");
            map.put("15", "内蒙古");
            map.put("21", "辽宁");
            map.put("22", "吉林");
            map.put("23", "黑龙江");
            map.put("31", "上海");
            map.put("32", "江苏");
            map.put("33", "浙江");
            map.put("34", "安徽");
            map.put("35", "福建");
            map.put("36", "江西");
            map.put("37", "山东");
            map.put("41", "河南");
            map.put("42", "湖北");
            map.put("43", "湖南");
            map.put("44", "广东");
            map.put("45", "广西");
            map.put("46", "海南");
            map.put("50", "重庆");
            map.put("51", "四川");
            map.put("52", "贵州");
            map.put("53", "云南");
            map.put("54", "西藏");
            map.put("61", "陕西");
            map.put("62", "甘肃");
            map.put("63", "青海");
            map.put("64", "宁夏");
            map.put("65", "新疆");
            map.put("71", "台湾");// 兼容原来的写法
            map.put("83", "台湾");// 台湾的身份证
            map.put("81", "香港");
            map.put("82", "澳门");
            map.put("91", "国外");
        }
        return map;
    }

    /**
     * 功能：判断字符串是否为数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (isNum.matches()) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isDate(String strDate) {
        Pattern pattern = Pattern
                .compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
        Matcher m = pattern.matcher(strDate);
        if (m.matches()) {
            return true;
        } else {
            return false;
        }
    }

}
